import '../configs/urls_config.dart';
import '../models/paged_result.dart';
import '../utils/http.dart';

class RestfulApiClient<T> {
  final String resourcePath;
  final T Function(Object) fromJson;

  RestfulApiClient({this.resourcePath, this.fromJson});

  Future<T> getById(String id) async {
    final Uri url = UrlsConfig.buildUrl("$resourcePath/$id");
    final json = await HttpUtil.instance.fetchJson(
      url,
      HttpOptions(
        method: 'GET',
      ),
    );

    return fromJson(json);
  }

  Future<PagedResult<T>> pagination({
    int page = 1,
    int limit = 20,
    String query,
    String orderBy,
  }) async {
    final Map<String, String> queryParameters = {
      'page': page.toString(),
      'limit': limit.toString(),
    };

    if (query != null) {
      queryParameters['query'] = query;
    }

    if (orderBy != null) {
      queryParameters['orderBy'] = orderBy;
    }

    final Uri url = UrlsConfig.buildUrl(resourcePath, queryParameters);
    dynamic json = await HttpUtil.instance.fetchJson(
      url,
      HttpOptions(
        method: 'GET',
      ),
    );

    return PagedResult<T>.fromJson(json, fromJson);
  }

  Future<T> create(dynamic data) async {
    final Uri url = UrlsConfig.buildUrl(resourcePath);
    dynamic json = await HttpUtil.instance.fetchJson(
      url,
      HttpOptions(
        method: 'POST',
        body: data,
      ),
    );

    return fromJson(json);
  }

  Future<T> update(String id, dynamic data) async {
    final Uri url = UrlsConfig.buildUrl("$resourcePath/$id");
    dynamic json = await HttpUtil.instance.fetchJson(
      url,
      HttpOptions(
        method: 'PUT',
        body: data,
      ),
    );

    return fromJson(json);
  }

  Future removeById(String id) async {
    final Uri url = UrlsConfig.buildUrl("$resourcePath/$id");
    await HttpUtil.instance.fetchJson(
      url,
      HttpOptions(
        method: 'DELETE',
      ),
    );
  }
}
